﻿using System.Linq;
using Myotragus.Data.Criteria;
using Myotragus.Data.Domain;
using Myotragus.Data.Util;

namespace Myotragus.Data.RepositoryExtensions
{
  public static class DefaultsLocalizableWriteRepositoryExtensions
  {
    public static IDefaultsLocalizableWriteRepository<TId, TEntity, TDescriptor, TProjector, TAlias> 
      SetDefaultLcId<TId, TEntity, TDescriptor, TProjector, TAlias>
      (
      this IDefaultsLocalizableWriteRepository<TId, TEntity, TDescriptor, TProjector, TAlias> @this,
      TEntity entity, int lcId
      )
      where TEntity : IEntity<TId>
      where TDescriptor : ILocalizableEntityDescriptor<TEntity>
      where TProjector : IProjector
      where TAlias : ILocalizableAlias
    {
      return @this.SetDefaultLcId(entity.Id, lcId);
    }

    public static IDefaultsLocalizableWriteRepository<TId, TEntity, TDescriptor, TProjector, TAlias> 
      SetDefaultLcId<TId, TEntity, TDescriptor, TProjector, TAlias>
      (
      this IDefaultsLocalizableWriteRepository<TId, TEntity, TDescriptor, TProjector, TAlias> @this,
      TId id, int lcId
      )
      where TEntity : IEntity<TId>
      where TDescriptor : ILocalizableEntityDescriptor<TEntity>
      where TProjector : IProjector
      where TAlias : ILocalizableAlias
    {
      var descriptor = LocalizableCriteriaHelper.ResolveEntityDescriptor(@this);
      using (var session = @this.OpenSession())
      {
        var save = session.Get(descriptor.SaveEntityImplementation, id);

        foreach (var text in descriptor.LocalizableProperties
					.Select(prop => (IDefaultsSaveLocalizableText)descriptor
						.SaveEntityProperties[prop].GetValue(save, ReflectionHelper.EmptyObjects)))
          text.DefaultLcId = lcId;

        using (var transaction = session.BeginTransaction())
        {
          session.Save(save);
          session.Flush();
          transaction.Commit();
        }
      }

      return @this;
    }
  }
}